package com.huang.springbootjspshiro.config;

import com.huang.springbootjspshiro.shiro.realm.CustomerRealm;
import com.huang.springbootjspshiro.shiro.redis.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class shiroconfig {

 //创建shiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
            factoryBean.setSecurityManager(manager);
            //设置系统首先资源
        Map<String, String> map = new HashMap<>();
        map.put("/user/login","anon");//设置公共资源
        map.put("/user/register","anon");//设置公共资源
        map.put("/register.jsp","anon");//设置公共页面
        map.put("/**","authc"); //受限资源
        //有个默认的认证资源 没认证默认跳转 login.jsp
        factoryBean.setLoginUrl("/login.jsp");

        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
            manager.setRealm(realm);
        return manager;
    }
    @Bean
    public Realm realm(){
        CustomerRealm realm = new CustomerRealm();
        //使用了盐 需要修改磨人的匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1024);
        realm.setCredentialsMatcher(matcher);

        //开启缓存管理
     //   realm.setCacheManager(new EhCacheManager());
        realm.setCacheManager(new RedisCacheManager());
        realm.setCachingEnabled(true); //开启全局缓存
        realm.setAuthenticationCachingEnabled(true); //开启认证缓存
        realm.setAuthenticationCacheName("authentiontionCache");
        realm.setAuthorizationCachingEnabled(true); //开启授权缓存
        realm.setAuthorizationCacheName("authenticationCache");
        return realm;
    }

}
